"use client"

import type React from "react"

import { createContext, useContext, useEffect, useState } from "react"
import type { User } from "./mock-data"

interface AuthContextType {
  user: User | null
  login: (email: string, password: string) => Promise<boolean>
  register: (userData: Partial<User>) => Promise<boolean>
  logout: () => void
  isLoading: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // Check for stored user session
    const storedUser = localStorage.getItem("currentUser")
    if (storedUser) {
      setUser(JSON.parse(storedUser))
    }
    setIsLoading(false)
  }, [])

  const login = async (email: string, password: string): Promise<boolean> => {
    setIsLoading(true)

    // Mock authentication - in real app, this would call your API
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // For demo purposes, accept any email/password combination
    const mockUser: User = {
      id: "1",
      username: "johndoe",
      displayName: "John Doe",
      email: email,
      avatar: "/placeholder.svg?height=100&width=100",
      bio: "Photography enthusiast 📸 | Travel lover ✈️ | Coffee addict ☕",
      followers: 1234,
      following: 567,
      posts: 89,
      verified: true,
      interests: ["photography", "travel", "coffee"],
      location: "New York, NY",
      joinDate: "2023-01-15",
    }

    setUser(mockUser)
    localStorage.setItem("currentUser", JSON.stringify(mockUser))
    setIsLoading(false)
    return true
  }

  const register = async (userData: Partial<User>): Promise<boolean> => {
    setIsLoading(true)

    // Mock registration
    await new Promise((resolve) => setTimeout(resolve, 1000))

    const newUser: User = {
      id: Date.now().toString(),
      username: userData.username || "",
      displayName: userData.displayName || "",
      email: userData.email || "",
      avatar: "/placeholder.svg?height=100&width=100",
      bio: userData.bio || "",
      followers: 0,
      following: 0,
      posts: 0,
      verified: false,
      interests: userData.interests || [],
      location: userData.location,
      joinDate: new Date().toISOString(),
    }

    setUser(newUser)
    localStorage.setItem("currentUser", JSON.stringify(newUser))
    setIsLoading(false)
    return true
  }

  const logout = () => {
    setUser(null)
    localStorage.removeItem("currentUser")
  }

  return <AuthContext.Provider value={{ user, login, register, logout, isLoading }}>{children}</AuthContext.Provider>
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
}
